﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using MusicStore.Silverlight.Helpers;
using MusicStore.Silverlight.MusicStoreService;
using MusicStore.Silverlight.ViewModels;
using System.Windows.Data;
using Castle.Core.Logging;
using MusicStore.Silverlight.Infrastructure;
using Structura.Silverlight.Infrastructure.ViewModel;

namespace MusicStore.Silverlight.Views
{
	public partial class Album : Page, IAlbumView
	{
		protected Album()
		{
			InitializeComponent();

			Loaded += Album_Loaded;
		}

		IViewModel IView.ViewModel { get; set; }

		public IAlbumViewModel ViewModel { get { return ((this as IView).ViewModel as IAlbumViewModel); } }

		public ILogger Logger { get; set; }

		public Album(IAlbumViewModel viewModel)
			: this()
		{
			(this as IView).ViewModel = viewModel;
			// this sets the view, we can use a facility to configure the objects
			// (ViewModel as IViewModel).View = this;
		}

		void Album_Loaded(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Initializng Album page");
		
			// use IoC to initialize this member variable
			//ViewModel = App.Container.Resolve<IAlbumViewModel>();

			// set the whole data context of the form
			DataContext = ViewModel;

			TextAuthor.Populating += TextAuthor_Populating;
			TextLabel.Populating += TextLabel_Populating;

			int id = 0;
			if (NavigationContext.QueryString.Count > 0)
			{
				object o = NavigationContext.QueryString["id"];
				if (o != null)
					id = Convert.ToInt32(o);
			}

			Logger.Info(string.Format("UI - Retrieving Album({0}) information", id));

			ViewModel.GetAlbum(id);
		}

		#region "autocomplete textbox"

		bool Filter(string prefix, object item)
		{
			if (string.IsNullOrEmpty(prefix))
			{
				return true;
			}
			string str = item as string;
			if (string.IsNullOrEmpty(str))
			{
				return false;
			}
			return str.ToLower().Contains(prefix.ToLower());
		}

		static void TextLabel_Populating(object sender, PopulatingEventArgs e)
		{
			AutoCompleteBox autoComplete = (AutoCompleteBox)sender;
			// Allow us to wait for the response
			e.Cancel = true;

			MusicStoreServiceClient client = ServiceHelper.GetServiceClient();
			client.GetLabelsFilterCompleted += (s2, e2) =>
																{
																	if (e2.Error == null)
																	{
																		List<string> data = e2.Result.Select(o => o.Name).ToList();
																		// Diplay the AutoCompleteBox drop down with any suggestions
																		autoComplete.ItemsSource = data;
																		autoComplete.PopulateComplete();
																	}
																};
			client.GetLabelsFilterAsync(autoComplete.Text);
		}

		static void TextAuthor_Populating(object sender, PopulatingEventArgs e)
		{
			AutoCompleteBox autoComplete = (AutoCompleteBox)sender;
			// Allow us to wait for the response
			e.Cancel = true;

			MusicStoreServiceClient client = ServiceHelper.GetServiceClient();
			client.GetAuthorsFilterCompleted += (s2, e2) =>
			{
				if (e2.Error == null)
				{
					List<string> data = e2.Result.Select(o => o.Name).ToList();
					// Diplay the AutoCompleteBox drop down with any suggestions
					autoComplete.ItemsSource = data;
					autoComplete.PopulateComplete();
				}
			};
			client.GetAuthorsFilterAsync(autoComplete.Text);
		}

		#endregion

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
		}

		private void BtnCancel_Click(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Cancel Pressed");

			NavigateAway();
		}

		private void BtnDelete_Click(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Delete Pressed");
			// delete the record
			ViewModel.DeleteAlbum();
		}

		private void BtnSave_Click(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Save Pressed");
			// save the album
			if (IsAlbumInputValid())
				ViewModel.SaveAlbum();
		}

		private void NavigateAway()
		{
			Logger.Info("UI - Navigating away from the Album Page");

			if (NavigationService.CanGoBack)
				NavigationService.GoBack();
			else
			{
				NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
			}
		}

		public void AlbumDeleted()
		{
			Logger.Info("UI - Album Deleted");

			NavigateAway();
		}

		public void AlbumSaved()
		{
			Logger.Info("UI - Album Saved");
			// do nothing now, just inform that the album was saved
			MessageBox.Show("Album Saved");
		}

		private void BtnAddTrack_Click(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Adding a Track");

			if (IsAlbumTrackValid())
				ViewModel.AddTrack(Convert.ToInt32(TextNumber.Text), TextTitle.Text, TextDuration.Text);
		}

		private void DeleteTrack_Click(object sender, RoutedEventArgs e)
		{
			Logger.Info("UI - Deleting a Track");

			ViewModel.RemoveTrack((Track)((Button)sender).Tag);
		}

		private void BtnUploadPreview_Click(object sender, RoutedEventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Multiselect = false;
			dlg.Filter = "JPG Images (*.jpg)|*.jpg";

			bool? retval = dlg.ShowDialog();
			if (retval != null && retval == true)
			{
				Logger.Info("UI - Uploading a preview file");

				ViewModel.UploadPreviewFile(dlg.File.OpenRead());
			}
		}

		#region "Validation"

		/// <summary>
		/// we need to force the validation framework to validate the control
		/// </summary>
		private bool IsAlbumInputValid()
		{
			BindingExpression be = TextAlbumTitle.GetBindingExpression(TextBox.TextProperty);
			be.UpdateSource();
			be = DpPubblicationDate.GetBindingExpression(DatePicker.SelectedDateProperty);
			be.UpdateSource();

			return (AlbumValidationSummary.Errors.Count == 0);
		}

		/// <summary>
		/// here we do some old-style validation with reporting (the validation is
		/// considered an input validation)
		/// </summary>
		/// <returns></returns>
		private bool IsAlbumTrackValid()
		{
			int number;
			if ((string.IsNullOrEmpty(TextNumber.Text) || (!int.TryParse(TextNumber.Text, out number))))
			{
				MessageBox.Show("A Number is Required!", "Number Validation", MessageBoxButton.OK);
				return false;
			}
			if (string.IsNullOrEmpty(TextTitle.Text))
			{
				MessageBox.Show("A Title is Required!", "Title Validation", MessageBoxButton.OK);
				return false;
			}
			return true;
		}

		#endregion
	}
}
